package cn.shyouchi.wuguanjia.android.ui.event.labor;

import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.squareup.timessquare.CalendarView;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.ui.event.checknum.CheckNumEntity;
import cn.shyouchi.wuguanjia.android.utils.ToastUtil;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import cn.shyouchi.wuguanjia.android.widget.dialog.LaborEditFragment;
import cn.shyouchi.wuguanjia.android.widget.dialog.PreviewLaborEditFragment;


public class TotalLaborActivity extends BaseActivity implements CalendarView.OnCalendarChangeListener,
        LaborContract.View,
        CalendarView.HeightDateClickListener {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.calendar_view)
    CalendarView mCalendarView;

    @BindView(R.id.tv_date)
    TextView tvDate;

    @BindView(R.id.tv_total_time)
    TextView mTvTotalTime;


    //班次列表
    List<RankTime.ResultMessageBean> mLaborEntities = new ArrayList<>();

    //一天的班次安排列表
    List<LaborRequestEntity.ResultMessageBean> dateLabors = new ArrayList<>();

    LaborPresenter mLaborPresenter;

    String projectId;

    @Override
    public int initContentView() {
        return R.layout.activity_total_labor;
    }

    @Override
    public void initInjector() {
        projectId = getIntent().getStringExtra("projectId");
        mLaborPresenter = new LaborPresenter(mContext, this);

    }

    @Override
    public void initUiAndListener() {
        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());
        mCalendarView.setOnCalendarChangeListener(this);
        mCalendarView.setOnHeightDateClickListener(this);
        tvDate.setText(new SimpleDateFormat("yyyy年MM月").format(mCalendarView.getDate()));
        mLaborPresenter.getRankList(projectId);
        mLaborPresenter.getLaborList(projectId, new SimpleDateFormat("yyyy-MM-dd").format(mCalendarView.getDate()));


    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }

    @OnClick({R.id.btnPri, R.id.btnNext})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnPri:
                priMonth();
                break;
            case R.id.btnNext:
                nextMonth();
                break;
        }
    }

    public void nextMonth() {
        mCalendarView.nextMonth();
        onDateChange();
    }

    public void priMonth() {
        mCalendarView.prevMonth();
        onDateChange();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add("设置");
        menuItem.setShowAsAction(2);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getTitle().equals("设置")) {
            if (!mCalendarView.getSelectedCells().isEmpty()) {
                if (!mLaborEntities.isEmpty()) {
                    LaborEditFragment dialog = LaborEditFragment.newInstance("");
                    dialog.setData(mLaborEntities);
                    dialog.setLaborDialogListener(new LaborEditFragment.LaborDialogListener() {
                        @Override
                        public void onDialogPositiveClick(List<RankTime.ResultMessageBean> mLaborEntities) {
                            List<LaborEntity> laborEntities = new ArrayList<LaborEntity>();
                            for (Calendar calendar : mCalendarView.getSelectedCells()) {
                                mCalendarView.addHeightCells(calendar);
                                laborEntities.add(new LaborEntity(calendar.getTime(), mLaborEntities));
                            }
                            if (!laborEntities.isEmpty()) {
                                mLaborPresenter.addLabor(projectId, laborEntities);
                                mCalendarView.clearSelectedCells();
                                mCalendarView.upCalendarView();
                            }
                        }
                    });
                    dialog.show(getSupportFragmentManager(), "");
                } else {
                    ToastUtil.showToast("班次列表为空");
                }
                return true;
            } else {
                ToastUtil.showToast("请选择日期");
            }
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onChange(Date date) {
        tvDate.setText(new SimpleDateFormat("yyyy年MM月").format(date));
//        mCalendarView.getSelectedCells().clear();
//        mCalendarView.upCalendarView();

    }


    @Override
    public void onDataRefresh(List<LaborRequestEntity.ResultMessageBean> resultMessageBeanList) {
        mCalendarView.clearHeightCells();
        this.dateLabors.clear();
        this.dateLabors.addAll(resultMessageBeanList);
        double totalTime = 0d;
        for (LaborRequestEntity.ResultMessageBean bean : resultMessageBeanList) {
            if (bean != null && bean.getService() != null && !bean.getService().isEmpty()) {
                mCalendarView.addHeightCells(covertTime(bean.getDate()));
            }
            totalTime = totalTime + CalculateTime(bean);
        }
        mCalendarView.upCalendarView();

        mTvTotalTime.setText(String.valueOf(new DecimalFormat("######0.00").format(totalTime)));
    }

    @Override
    public void onItemClick(CheckNumEntity.ResultMessageBean bean) {

    }

    @Override
    public void onDelClick(CheckNumEntity.ResultMessageBean bean) {

    }

    @Override
    public void onEditClick(CheckNumEntity.ResultMessageBean bean) {

    }

    @Override
    public void onRankRefresh(List<RankTime.ResultMessageBean> resultMessageBeanList) {
        mLaborEntities.clear();
        mLaborEntities.addAll(resultMessageBeanList);
    }

    @Override
    public void onHeightDateClick(final Date date) {

        final LaborRequestEntity.ResultMessageBean en = getDateLaborByDate(date);

        PreviewLaborEditFragment dialog = PreviewLaborEditFragment.newInstance("");

        dialog.setData(mLaborEntities);
        dialog.setLabor(en);
        dialog.setLaborDialogListener(new PreviewLaborEditFragment.LaborDialogListener() {
            @Override
            public void onDialogPositiveClick(List<RankTime.ResultMessageBean> mLaborEntities) {
                List<LaborEntity> laborEntities = new ArrayList<LaborEntity>();
                laborEntities.add(new LaborEntity(date, mLaborEntities));
                if (!laborEntities.isEmpty()) {
                    mLaborPresenter.addLabor(projectId, laborEntities);
                }
            }

            @Override
            public void onDelClick() {
                mLaborPresenter.delLabor(projectId, String.valueOf(en.getId()));
            }
        });

        dialog.show(getSupportFragmentManager(), "");

    }

    @Override
    public void onDateChange() {
        mCalendarView.getSelectedCells().clear();
        mCalendarView.upCalendarView();
        mLaborPresenter.getRankList(projectId);
        mLaborPresenter.getLaborList(projectId, new SimpleDateFormat("yyyy-MM-dd").format(mCalendarView.getDate()));
    }

    public Calendar covertTime(String time) {
        Calendar dayc1 = new GregorianCalendar();
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        Date daystart = null;
        try {
            daystart = df.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        dayc1.setTime(daystart);
        return dayc1;
    }

    public double CalculateTime(LaborRequestEntity.ResultMessageBean bean) {
        double time = 0d;


        for (LaborRequestEntity.ResultMessageBean.ServiceBeanX serviceBeanX : bean.getService()) {
            time = time + serviceBeanX.getService().getTime() * serviceBeanX.getService_people();
        }


        return time;
    }


    private LaborRequestEntity.ResultMessageBean getDateLaborByDate(Date date) {
        String day = new SimpleDateFormat("yyyy-MM-dd").format(date);
        for (LaborRequestEntity.ResultMessageBean b : this.dateLabors) {
            if (b.getDate().equals(day)) {
                return b;
            }
        }
        return null;
    }


}
